//
//  UgcCommentKewboardV.m
//  ZITHER
//
//  Created by weixin on 2018/9/18.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "UgcCommentKewboardV.h"
#define kScreenBounds ([[UIScreen mainScreen] bounds])
#define kScreenwidth (kScreenBounds.size.width)
#define kScreenheight (kScreenBounds.size.height)
#define UIColorRGB(x,y,z) [UIColor colorWithRed:x/255.0 green:y/255.0 blue:z/255.0 alpha:1.0]
@interface UgcCommentKewboardV()<UITextViewDelegate,UIScrollViewDelegate>
{
    BOOL statusTextView;//当文字大于限定高度之后的状态
    NSString *placeholderText;//设置占位符的文字
}
@property (nonatomic, strong) UIView *backGroundView;
@property (nonatomic, strong) UILabel *placeholderLabel;
@property (nonatomic, strong) UIButton *sendButton;
@end


@implementation UgcCommentKewboardV

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.keyboardState = YES;

        [self createUI];
        //增加监听，当键盘出现或改变时收出消息
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotification object:nil];
        //增加监听，当键退出时收出消息
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotification
                                                   object:nil];
    }
    
    /**
     点击 空白区域取消
     */
    UITapGestureRecognizer *centerTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(centerTapClick)];
    [self addGestureRecognizer:centerTap];
    return self;
}

- (void)createUI{
    
    [self addSubview:self.Reply];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
            make.top.mas_equalTo(0);
//            make.top.equalTo(self).offset(10);

//            make.bottom.equalTo(self).offset(-kBottomSafeHeight);
        }else{
//            make.bottom.equalTo(self).offset(-kBottomSafeHeight);
            make.bottom.mas_equalTo(-6);

        }
        
        make.left.equalTo(self).offset(5);
//        make.bottom.mas_equalTo(-6);
        make.width.mas_equalTo(kScreenwidth-65);
        make.height.mas_equalTo(40);

    }];
    
    [self.placeholderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(5);
        make.left.mas_equalTo(10);
        make.height.mas_equalTo(39);
    }];
    
    if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
        [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.mas_equalTo(16);
            make.centerY.equalTo(self.textView.mas_centerY).offset(5);

            make.right.mas_equalTo(-15);
            make.width.height.mas_equalTo(20);
        }];
        
    }else{
        [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(14);
            make.right.mas_equalTo(-5);
            make.width.mas_equalTo(50);
        }];
    }


    
}


//暴露的方法
- (void)setPlaceholderText:(NSString *)text{
    placeholderText = text;
    self.placeholderLabel.text = placeholderText;
}

//带字展开
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    
//    if (!kUSER_INFO_MANAGER.userIsLogin) {
//        [self.textView endEditing:YES];
//        [Tools pushSinge];
//        return ;
//    }
   
    self.keyboardState = NO;
    if ( self.Reply.text.length == 0) {
         self.Reply.hidden = YES;
    }else{
        self.Reply.hidden = NO;
    }
    
    self.frame = kScreenBounds;
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    
    if (self.textView.text.length == 0) {
        
        self.backGroundView.frame = CGRectMake(0, kScreenheight-height-49, kScreenwidth, 49);
        CGRect rect = CGRectMake(0, 0, kScreenwidth, self.backGroundView.frame.size.height);
        self.backGroundView.frame = rect;
        self.frame = CGRectMake(0, kScreenheight - rect.size.height, kScreenwidth, self.backGroundView.frame.size.height);
        
    }else{
        self.backGroundView.frame = CGRectMake(0, kScreenheight-height-49, kScreenwidth, 49);
        CGRect rect = CGRectMake(0, 0, kScreenwidth, self.backGroundView.frame.size.height);
        self.backGroundView.frame = rect;
        self.frame = CGRectMake(0, kScreenheight - rect.size.height, kScreenwidth, self.backGroundView.frame.size.height);
        
        
//        CGRect rect = CGRectMake(0, kScreenheight - self.backGroundView.frame.size.height-height, kScreenwidth, self.backGroundView.frame.size.height);
//        self.backGroundView.frame = rect;
//        self.frame = CGRectMake(0, kScreenH -height, kScreenwidth, self.backGroundView.frame.size.height);
    }
    //{0, 465}, {414, 49}
    //{0, 465}, {414, 49}
    NSLog(@"self.frame ====== %@",NSStringFromCGRect(self.frame));

}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    self.keyboardState = YES;
    self.Reply.hidden = YES;
    if (self.textView.text.length == 0) {
        self.backGroundView.frame = CGRectMake(0, 0, kScreenwidth, 49);
        self.frame = CGRectMake(0, kScreenheight-49-kBottomSafeHeight, kScreenwidth, 49);
    }else{
        CGRect rect = CGRectMake(0, 0, kScreenwidth, self.backGroundView.frame.size.height);
        self.backGroundView.frame = rect;
        self.frame = CGRectMake(0, kScreenheight - rect.size.height-kBottomSafeHeight, kScreenwidth, self.backGroundView.frame.size.height);
    }
}

- (void)centerTapClick{
    [self.textView resignFirstResponder];
}


#pragma mark --- UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    /**
     *  设置占位符
     */
    if (textView.text.length == 0) {
        self.placeholderLabel.text = placeholderText;
//        [self.sendButton setBackgroundColor:UIColorRGB(180, 180, 180)];
        self.sendButton.userInteractionEnabled = NO;
    }else{
        self.placeholderLabel.text = @"";
//        [self.sendButton setBackgroundColor:UIColorRGB(70 , 163, 231)];
        self.sendButton.userInteractionEnabled = YES;
    }
    
    //---- 计算高度 ---- //
    CGSize size = CGSizeMake(kScreenwidth-65, CGFLOAT_MAX);
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12],NSFontAttributeName, nil];
    CGFloat curheight = [textView.text boundingRectWithSize:size
                                                    options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                 attributes:dic
                                                    context:nil].size.height;
    CGFloat y = CGRectGetMaxY(self.backGroundView.frame);
    if (curheight < 19.094) {
        statusTextView = NO;
        self.backGroundView.frame = CGRectMake(0, y - 49, kScreenwidth, 49);
    }else if(curheight < MaxTextViewHeight){
        statusTextView = NO;
        self.backGroundView.frame = CGRectMake(0, y - textView.contentSize.height-10, kScreenwidth,textView.contentSize.height+10);
    }else{
        statusTextView = YES;
        return;
    }
    
    if (self.blockUPHeight) {
        self.blockUPHeight();
    }

}

#pragma  mark -- 发送事件
- (void)sendClick:(UIButton *)sender{
    [self.textView endEditing:YES];
    
    if (self.type == 0) {
     	   /** 回复详情页 */
        if (self.EwenTextViewBlock) {
            self.EwenTextViewBlock(self.textView.text);
        }
        
    }else if (self.type == 1){
 
                [[serviceDefualt loadAddSonComment:self.relId replyUserId:self.replyUserId
                                           relType:self.relType commentParentId:self.commentParentId commentMasterId:self.commentMasterId commentContent:self.textView.text reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
                    if (x.success) {
                        [Tools showTips:@"评论成功"];
                        /** 回复详情页 */
                        if (self.sendSubComment) {
                               UgcCommentListModelSub * modelComment = [UgcCommentListModelSub yy_modelWithDictionary:x.responseRawData[@"data"]];
                            self.sendSubComment(modelComment);
                        }
                    }else{
                        [Tools showTips:x.errorInfo];
                    }
                }];

    }else{
        [[serviceDefualt loadAddSonComment:self.relId replyUserId:self.replyUserId relType:self.relType commentParentId:self.commentParentId commentMasterId:self.commentMasterId commentContent:self.textView.text reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
            if (x.success) {
                [Tools showTips:@"评论成功"];
                /** 回复详情页 */
                if (self.sendSubComment) {
                       UgcCommentListModelSub * modelComment = [UgcCommentListModelSub yy_modelWithDictionary:x.responseRawData[@"data"]];
                    self.sendSubComment(modelComment);
                }
            }else{
                [Tools showTips:x.errorInfo];
            }
        }];
        
    }
    
    self.type = 0;
    
    //---- 发送成功之后清空 ------//
    self.textView.text = nil;
    self.placeholderLabel.text = placeholderText;
//    [self.sendButton setBackgroundColor:UIColorRGB(180, 180, 180)];
    self.sendButton.userInteractionEnabled = NO;
    self.frame = CGRectMake(0, kScreenheight-49, kScreenwidth, 49);
    self.backGroundView.frame = CGRectMake(0, 0, kScreenwidth, 49);
}



#pragma mark --- 懒加载控件
- (UIView *)backGroundView{
    if (!_backGroundView) {
        _backGroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenwidth, 49)];
        _backGroundView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_backGroundView];
    }
    return _backGroundView;
}

- (UITextView *)textView{
    if (!_textView) {
        _textView = [[UITextView alloc]init];
        
        _textView.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:15];
        
        _textView.delegate = self;
        _textView.layer.cornerRadius = 5;
        [self.backGroundView addSubview:_textView];
        _textView.enablesReturnKeyAutomatically = YES;
        _textView.tintColor = baseColorLight;
   
        _textView.keyboardAppearance = UIKeyboardAppearanceDefault;
        _textView.returnKeyType = UIReturnKeyNext;
        [self.backGroundView addSubview:_textView];
        
        if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
            _textView.backgroundColor = RGB(244, 244, 244);
            [_textView setCornerRadiusWithRadius:20 isMasks:YES];
        }else{
            _textView.qmui_borderPosition = QMUIViewBorderPositionBottom;
            _textView.qmui_borderWidth = 2;
            _textView.qmui_borderColor = baseColorLight;
        }
        

        
        
        
        
        
        //        _textView.returnKeyType = UIReturnKeyDone;
        
        //        _textView.typingAttributes = @{NSFontAttributeName: UIFontMake(35),
        //                                  NSForegroundColorAttributeName: [UIColor whiteColor],
        //                                  NSParagraphStyleAttributeName: [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:40]};
        // 限制可输入的字符长度
        //        _textView.maximumZoomScale = 300;//设置最大缩放
        
    }
    return _textView;
}

- (UILabel *)placeholderLabel{
    if (!_placeholderLabel) {
        _placeholderLabel = [[UILabel alloc]init];
        _placeholderLabel.font = [UIFont systemFontOfSize:12];
        _placeholderLabel.textColor = [UIColor grayColor];
        [self.backGroundView addSubview:_placeholderLabel];
    }
    return _placeholderLabel;
}

- (UIButton *)sendButton{
    if (!_sendButton) {
        if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
            _sendButton = [BaseBtn initCustomBtn:@[@"评论"]];
            _sendButton.frame = CGRectMake(14,kStatusBarHeight+5,40,40);
        }else{
            _sendButton = [BaseBtn initCustomBtnTitlestype:@[@"发布"] color:@[baseColorTheme]];
            _sendButton.frame = CGRectMake(14,kStatusBarHeight+5,40,20);
            _sendButton.titleLabel.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:15];
        }

        [_sendButton addTarget:self action:@selector(sendClick:) forControlEvents:UIControlEventTouchUpInside];
        _sendButton.layer.cornerRadius = 5;
        _sendButton.userInteractionEnabled = NO;
        [self.backGroundView addSubview:_sendButton];
    }
    return _sendButton;
}

#pragma mark --- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (statusTextView == NO) {
        scrollView.contentOffset = CGPointMake(0, 0);
    }else{
        
    }
}


- (QMUILabel *)Reply{
    if (!_Reply) {
        _Reply = [[QMUILabel alloc]initWithFrame:CGRectMake(0, -40, kScreenW, 40)];
        _Reply.font =[UIFont systemFontOfSize:18];
        _Reply.textAlignment = 1;
        _Reply.backgroundColor = [UIColor whiteColor];
        _Reply.hidden = YES;
        _Reply.userInteractionEnabled = NO;
    }
    return _Reply;
}





@end

